/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.common.prometheus.converter.result;

import com.dsms.common.prometheus.converter.Data;
import com.dsms.common.prometheus.converter.Result;
import lombok.EqualsAndHashCode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EqualsAndHashCode(callSuper = true)
@lombok.Data
public class DefaultQueryResult<T extends Data> extends Result<T> {
    List<T> result = new ArrayList<>();

    public <U> U getQueryResult() {
        if (result == null || result.isEmpty()) {
            return null;
        }
        T t = result.get(0);
        if (t instanceof MatrixData) {
            return (U) ((MatrixData) t).getRangeQueryResult();
        } else if (t instanceof VectorData) {
            return (U) ((VectorData) t).getDataValue();
        }
        return null;
    }

    public <U> Map<String, U> getQueryResultAll(String metric) {
        if (result == null || result.isEmpty()) {
            return Collections.emptyMap();
        }
        Map<String, U> resultMap = new HashMap<>();
        for (T t : result) {
            if (t instanceof MatrixData) {
                double[][] rangeQueryResult = ((MatrixData) t).getRangeQueryResult();
                resultMap.put(((MatrixData) t).getMetric().get(metric), (U) rangeQueryResult);
            } else if (t instanceof VectorData) {
                QueryResultItemValue dataValue = ((VectorData) t).getDataValue();
                resultMap.put(((VectorData) t).getMetric().get(metric), (U) dataValue);
            }
        }

        return resultMap;
    }

    public void addData(T data) {
        result.add(data);
    }
}
